package cn.ctyun.xstore.s3.api.bucket;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.GetBucketLocationRequest;

public class CreateBucket {

    public static void createBucket(String bucketName, AmazonS3 s3) {
        createBucketWithACL(bucketName, null, s3);
    }

    /**
     * 创建bucket
     *
     * @param bucketName
     * @param cannedAcl  bucket的访问权限
     */
    public static void createBucketWithACL(String bucketName, CannedAccessControlList cannedAcl, AmazonS3 s3) {
        try {
            if (!s3.doesBucketExistV2(bucketName)) {
                // Because the CreateBucketRequest object doesn't specify a region, the
                // bucket is created in the region specified in the client.
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName, "");
                if (cannedAcl != null) {
                    createBucketRequest.setCannedAcl(cannedAcl);
                }
                s3.createBucket(createBucketRequest);
                // Verify that the bucket was created by retrieving it and checking its location.
                String bucketLocation = s3.getBucketLocation(new GetBucketLocationRequest(bucketName));
                System.out.println("Bucket location: " + bucketLocation);
            } else {
                System.out.println("bucket已存在");
            }
        } catch (SdkClientException e) {
            e.printStackTrace();
        }
    }
}